package com.cqie.practicaltraining.config.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cqie.practicaltraining.config.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private UserDetailsService userDetailsService;

    @Value("${login.white.list}")
    private String[] whiteList;

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String requestURI = servletRequest.getRequestURI();

        // 检查请求 URI 是否在白名单中
        if (isWhiteList(requestURI)) {
            logger.info("Skipping white list request: {}", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 跳过 /api/login 请求
        if ("/api/login".equals(requestURI)) {
            logger.info("Skipping /login request in JwtAuthenticationTokenFilter");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 1. 从当前请求中获取到授权数据
        String token = servletRequest.getHeader("Authorization");

        // 2. 判断获取到的请求头中是否存在token
        if (StringUtils.isBlank(token)) {
            responseWrite(servletResponse, "请携带token");
            return;
        }

        // 从token中获取到当前登录用户的用户名
        String username = jwtTokenUtil.getUserNameFromToken(token);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 执行登录操作
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(token, username)) {
                // 设置认证信息
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(servletRequest));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            } else {
                responseWrite(servletResponse, "无效的token");
                return;
            }
        }else{
            responseWrite(servletResponse, "无效的token");
        }

        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean isWhiteList(String requestURI) {
        for (String pattern : whiteList) {
            if (pathMatcher.match(pattern, requestURI)) {
                return true;
            }
        }
        return false;
    }

    private void responseWrite(HttpServletResponse servletResponse, String message) throws IOException {
        // 设置编码格式
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("application/json");
        PrintWriter out = servletResponse.getWriter();
        out.write("{\"message\": \"" + message + "\"}");
        out.flush();
        out.close();
    }
}
